package com.xzx.study;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class InnerFileActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = InnerFileActivity.class.getSimpleName();

    private Button save_inner_file;
    private Button read_inner_file;
    private ImageView inner_file_image_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inner_file);

        save_inner_file = findViewById(R.id.save_inner_file);
        save_inner_file.setOnClickListener(this);
        read_inner_file = findViewById(R.id.read_inner_file);
        read_inner_file.setOnClickListener(this);
        inner_file_image_view = findViewById(R.id.inner_file_image_view);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.save_inner_file) {
            try {
                FileOutputStream fileOutputStream = openFileOutput("logo.png", MODE_PRIVATE);

                AssetManager assetManager = getAssets();
                InputStream inputStream = assetManager.open("logo.png");
                byte[] bytes =  new byte[1024 * 1024];
                int len = -1;
                while ((len = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, len);
                }
                fileOutputStream.close();
                inputStream.close();
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (v.getId() == R.id.read_inner_file) {
            try {
//                FileInputStream fileInputStream = openFileInput("logo.png");
                File filesDir = getFilesDir();
                Log.i(TAG, "filesDir=" + filesDir);// /data/user/0/com.xzx.study/files
                Bitmap bitmap = BitmapFactory.decodeFile(filesDir.getAbsolutePath() + "/logo.png");
                inner_file_image_view.setImageBitmap(bitmap);
                Toast.makeText(this, "读取成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
